package com.yunshipei.ui.activity;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.yunshipei.base.BaseLoginActivity;
import com.yunshipei.common.Globals;
import com.yunshipei.core.utils.SystemUtils;
import com.yunshipei.enterplorer.R;
import com.yunshipei.ui.view.TextWatcherAdapter;
import com.yunshipei.utils.BaseUtil;
import com.yunshipei.utils.ToastUtils;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTouch;

public class EnterplorerURLActivity extends BaseLoginActivity {

    @Bind(R.id.et_manager_server)
    protected EditText mEnterURLEditText;
    @Bind(R.id.et_manager_proxy)
    protected EditText mProxyEditText;
    @Bind(R.id.tv_back_login)
    protected View mBack;
    @Bind(R.id.tv_clear_pass)
    protected View mResetUrl;
    @Bind(R.id.btn_confirm)
    protected Button btnConfirm;
    @Bind(R.id.iv_clear_manager_server)
    protected ImageView ivClearManagerServer;
    @Bind(R.id.iv_clear_proxy)
    protected ImageView ivClearProxy;
    @Bind(R.id.rl_login_content_edit)
    protected RelativeLayout mContentRl;

    private SharedPreferences mSharedPref;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_enterplorer_url);
        ButterKnife.bind(this);
        mSharedPref = getSharedPreferences(Globals.NO_CLEAR_SHP, MODE_PRIVATE);
        String managerServer = mSharedPref.getString(Globals.MANUAL_BASE_URL, "");
        mEnterURLEditText.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                ivClearManagerServer.setVisibility(s.length() == 0 ? View.GONE : View.VISIBLE);
            }
        });
        mEnterURLEditText.setText(managerServer);
        mEnterURLEditText.setSelection(mEnterURLEditText.getText().toString().length());
        String proxy = mSharedPref.getString(Globals.PROXY_SERVER, "");
        mProxyEditText.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                ivClearProxy.setVisibility(s.length() == 0 ? View.GONE : View.VISIBLE);
            }
        });
        mProxyEditText.setText(proxy);
        mProxyEditText.setSelection(mProxyEditText.getText().toString().length());
        btnConfirm.setEnabled(true);
        btnConfirm.setAlpha(1.0f);
        if (SystemUtils.isPad(this)) {
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mContentRl.getLayoutParams();
            layoutParams.width = (int) ((BaseUtil.getStandSize(this) * 4) / 5);
            mContentRl.setLayoutParams(layoutParams);
        }
    }

    @OnClick({R.id.btn_confirm, R.id.tv_back_login, R.id.tv_clear_pass, R.id.iv_clear_manager_server, R.id.iv_clear_proxy})
    public void onSubmit(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.btn_confirm:
                saveManagerConfig();
                break;
            case R.id.tv_back_login:
                finish();
                break;
            case R.id.tv_clear_pass:
                mEnterURLEditText.setText("");
                mProxyEditText.setText("");
                break;
            case R.id.iv_clear_proxy:
                mProxyEditText.setText("");
                break;
            case R.id.iv_clear_manager_server:
                mEnterURLEditText.setText("");
                break;
        }
    }

    private void saveManagerConfig() {
        String managerURL = BaseUtil.replaceBlank(mEnterURLEditText.getText().toString().trim());
        String proxyIP = "";
        int proxyPort = 0;
        String url = BaseUtil.replaceBlank(mProxyEditText.getText().toString());
        if (!TextUtils.isEmpty(url)) {
            Uri uri = Uri.parse(url);
            if (uri == null) {
                ToastUtils.showToast("代理服务器地址无效");
                return;
            }
            proxyIP = uri.getHost();
            proxyPort = uri.getPort();
            if (proxyPort == -1) {
                proxyPort = 80;
            }
        }
        if (!TextUtils.isEmpty(proxyIP) && proxyPort != 0) {
            mSharedPref.edit().putString(Globals.PROXY_SERVER, url).putString(Globals.MANUAL_PROXY, proxyIP).putInt(Globals.MANUAL_PROXY_PORT, proxyPort).apply();
        } else {
            mSharedPref.edit().putString(Globals.PROXY_SERVER, "").putString(Globals.MANUAL_PROXY, "").putInt(Globals.MANUAL_PROXY_PORT, 0).apply();
        }
        if (!TextUtils.isEmpty(managerURL)) {
            if (BaseUtil.isURLAvailable(managerURL)) {
                mSharedPref.edit().putString(Globals.MANUAL_BASE_URL, managerURL).apply();
            } else {
                ToastUtils.showToast("EnterManager服务器地址无效，请检查重试...");
                return;
            }
        } else {
            mSharedPref.edit().putString(Globals.MANUAL_BASE_URL, "").apply();
        }

        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && this.getCurrentFocus() != null) {
            if (this.getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        finish();
    }

    @OnTouch(R.id.rl_root_view)
    protected boolean onViewTouchEvent() {
        BaseUtil.hideKeyBoard(this);
        return false;
    }
}
